package org.example.service.impl;

import org.example.entity.Account;
import org.example.entity.Token;
import org.example.feign.CodeFeignClient;
import org.example.repository.AccountRepository;
import org.example.repository.TokenRepository;
import org.example.service.AccountService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {

    private final AccountRepository accountRepository;
    private final CodeFeignClient codeFeignClient;
    private final TokenRepository tokenRepository;

    @Override
    public int register(String email, String password, String code) {
        int validate = codeFeignClient.validate(email, code);
        if (validate == 0){
            Boolean registered = isRegistered(email);
            if (registered){
                return 2;
            }
            Account account = new Account();
            account.setName(email);
            account.setPassword(password);
            accountRepository.save(account);
            return 0;
        }
        if (validate == 2){
            return 1;
        }
        if (validate == 1){
            return 3;
        }
        return validate;
    }

    @Override
    public Boolean isRegistered(String email) {
        Account account = new Account();
        account.setName(email);
        Example<Account> example = Example.of(account);
        long count = accountRepository.count(example);
        return count > 0;
    }

    @Override
    public String login(String email, String password) {
        Account account = new Account();
        account.setName(email);
        account.setPassword(password);
        Example<Account> example = Example.of(account);
        long count = accountRepository.count(example);
        if (count > 0){
            String tok = UUID.randomUUID().toString().replace("-", "");
            Token ken = new Token();
            ken.setEmail(email);
            Example<Token> exa = Example.of(ken);
            //如果token存在则修改， 不存在则新增
            Optional<Token> one = tokenRepository.findOne(exa);
            Token token = new Token();
            one.ifPresent(value -> token.setId(value.getId()));
            token.setEmail(email);
            token.setToken(tok);
            tokenRepository.save(token);
            return tok;
        }
        return null;
    }

    @Override
    public String info(String token) {
        Token tokenEntity = new Token();
        tokenEntity.setToken(token);
        Example<Token> example = Example.of(tokenEntity);
        Optional<Token> one = tokenRepository.findOne(example);
        return one.map(Token::getEmail).orElse(null);
    }
}
